<template>
  <div class="tencent-map-container">
    <div ref="mapContainer" class="map-container"></div>
    <div class="map-controls">
      <el-button 
        type="primary" 
        size="small" 
        @click="centerToUserLocation"
        :loading="locating"
      >
        <el-icon><Location /></el-icon>
        我的位置
      </el-button>
      <el-button 
        type="default" 
        size="small" 
        @click="toggleMapType"
      >
        {{ mapType === 'roadmap' ? '卫星图' : '街道图' }}
      </el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, watch, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { Location } from '@element-plus/icons-vue'
import { MAP_CONFIG, isMapApiKeyConfigured } from '@/config/map'

const props = defineProps({
  // 房源数据列表
  roomList: {
    type: Array,
    default: () => []
  },
  // 地图中心点
  center: {
    type: Object,
    default: () => MAP_CONFIG.DEFAULT_CENTER
  },
  // 地图缩放级别
  zoom: {
    type: Number,
    default: MAP_CONFIG.DEFAULT_ZOOM
  },
  // 是否显示房源标记
  showMarkers: {
    type: Boolean,
    default: true
  }
})

const emit = defineEmits(['marker-click', 'map-click', 'map-ready'])

const mapContainer = ref(null)
const map = ref(null)
const markers = ref([])
const locating = ref(false)
const mapType = ref('roadmap')

// 初始化地图
const initMap = async () => {
  if (!window.TMap) {
    ElMessage.error('腾讯地图SDK加载失败，请检查网络连接')
    return
  }

  if (!isMapApiKeyConfigured()) {
    ElMessage.warning('请先配置腾讯地图API密钥')
    return
  }

  try {
    // 创建地图实例
    map.value = new window.TMap.Map(mapContainer.value, {
      center: new window.TMap.LatLng(props.center.lat, props.center.lng),
      zoom: props.zoom,
      mapTypeId: 1 // 使用数字常量：1=街道图，2=卫星图
    })

    // 地图点击事件
    map.value.on('click', (evt) => {
      emit('map-click', {
        lat: evt.latLng.lat,
        lng: evt.latLng.lng
      })
    })

    // 地图加载完成
    map.value.on('tilesloaded', () => {
      emit('map-ready', map.value)
    })

    // 如果显示标记且有房源数据，创建标记
    if (props.showMarkers && props.roomList.length > 0) {
      createMarkers()
    }

  } catch (error) {
    console.error('地图初始化失败:', error)
    ElMessage.error(`地图初始化失败: ${error.message || '未知错误'}`)
  }
}

// 创建房源标记
const createMarkers = () => {
  if (!map.value || !props.roomList.length) return

  // 清除现有标记
  clearMarkers()

  const markerList = []
  
  props.roomList.forEach((room, index) => {
    // 检查房源是否有坐标信息
    if (room.latitude && room.longitude) {
      const marker = new window.TMap.MultiMarker({
        map: map.value,
        styles: {
          default: new window.TMap.MarkerStyle({
            width: 30,
            height: 30,
            anchor: { x: 15, y: 15 },
            src: 'data:image/svg+xml;base64,' + btoa(`
              <svg width="30" height="30" viewBox="0 0 30 30" xmlns="http://www.w3.org/2000/svg">
                <circle cx="15" cy="15" r="12" fill="#1890ff" stroke="#fff" stroke-width="2"/>
                <text x="15" y="20" text-anchor="middle" fill="white" font-size="12" font-weight="bold">${index + 1}</text>
              </svg>
            `)
          })
        },
        geometries: [{
          position: new window.TMap.LatLng(room.latitude, room.longitude),
          id: room.id,
          properties: {
            title: room.title || room.houseTitle,
            price: room.price || room.rentPriceListing,
            address: room.address || room.location
          }
        }]
      })

      // 标记点击事件
      marker.on('click', (evt) => {
        const geometry = evt.geometry
        emit('marker-click', {
          room: room,
          position: {
            lat: geometry.position.lat,
            lng: geometry.position.lng
          }
        })
      })

      markerList.push(marker)
    }
  })

  markers.value = markerList

  // 如果有标记，调整地图视野以包含所有标记
  if (markerList.length > 0) {
    fitMapToMarkers()
  }
}

// 清除所有标记
const clearMarkers = () => {
  markers.value.forEach(marker => {
    marker.setMap(null)
  })
  markers.value = []
}

// 调整地图视野以包含所有标记
const fitMapToMarkers = () => {
  if (!map.value || markers.value.length === 0) return

  const bounds = new window.TMap.LatLngBounds()
  
  markers.value.forEach(marker => {
    const geometries = marker.getGeometries()
    geometries.forEach(geometry => {
      bounds.extend(geometry.position)
    })
  })

  map.value.fitBounds(bounds, {
    padding: 50
  })
}

// 定位到用户位置
const centerToUserLocation = () => {
  if (!navigator.geolocation) {
    ElMessage.error('您的浏览器不支持定位功能')
    return
  }

  locating.value = true

  navigator.geolocation.getCurrentPosition(
    (position) => {
      const lat = position.coords.latitude
      const lng = position.coords.longitude
      
      if (map.value) {
        map.value.setCenter(new window.TMap.LatLng(lat, lng))
        map.value.setZoom(15)
      }
      
      locating.value = false
      ElMessage.success('定位成功')
    },
    (error) => {
      console.error('定位失败:', error)
      locating.value = false
      
      let message = '定位失败'
      switch (error.code) {
        case error.PERMISSION_DENIED:
          message = '用户拒绝了定位请求'
          break
        case error.POSITION_UNAVAILABLE:
          message = '位置信息不可用'
          break
        case error.TIMEOUT:
          message = '定位请求超时'
          break
      }
      ElMessage.error(message)
    },
    {
      enableHighAccuracy: true,
      timeout: 10000,
      maximumAge: 60000
    }
  )
}

// 切换地图类型
const toggleMapType = () => {
  if (!map.value) return

  mapType.value = mapType.value === 'roadmap' ? 'satellite' : 'roadmap'
  map.value.setMapTypeId(
    mapType.value === 'roadmap' ? 1 : 2 // 1=街道图，2=卫星图
  )
}

// 监听房源数据变化
watch(() => props.roomList, () => {
  if (map.value && props.showMarkers) {
    createMarkers()
  }
}, { deep: true })

// 监听中心点变化
watch(() => props.center, (newCenter) => {
  if (map.value && newCenter) {
    map.value.setCenter(new window.TMap.LatLng(newCenter.lat, newCenter.lng))
  }
}, { deep: true })

onMounted(() => {
  nextTick(() => {
    initMap()
  })
})

onBeforeUnmount(() => {
  if (map.value) {
    map.value.destroy()
  }
  clearMarkers()
})
</script>

<style scoped>
.tencent-map-container {
  position: relative;
  width: 100%;
  height: 100%;
  min-height: 400px;
}

.map-container {
  width: 100%;
  height: 100%;
  border-radius: 8px;
  overflow: hidden;
}

.map-controls {
  position: absolute;
  top: 10px;
  right: 10px;
  display: flex;
  flex-direction: column;
  gap: 8px;
  z-index: 1000;
}

.map-controls .el-button {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}
</style>
